package com.jiadakeji.ppm.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.xml.bind.ValidationEventHandler;
import javax.xml.bind.annotation.adapters.XmlAdapter;

/**
 *
 * 注解使用， 对象与xml转换的字段需要有 <![CDATA[]]>
 *
 * @Author xuelongjiang
 */
public class CDataAdapter extends XmlAdapter<String,String> {

    private static Logger logger = LoggerFactory.getLogger(CDataAdapter.class);

    /**
     * Do-nothing constructor for the derived classes.
     */
    protected CDataAdapter() {
        super();
    }

    /**
     * Convert a value type to a bound type.
     *
     * @param v The value to be converted. Can be null.
     * @throws Exception if there's an error during the conversion. The caller is responsible for
     *                   reporting the error to the user through {@link ValidationEventHandler}.
     */
    @Override
    public String unmarshal(String v) throws Exception {

      if("<![CDATA[]]>".equals(v)){
          return "";
      }
      String v1 = null;
      String v2 = null;

      String subStart = "<![CDATA[";
      int a = v.indexOf(subStart);
      if(a>= 0){
          v1 = v.substring(subStart.length(),v.length());

      }else {
          return v;
      }
      String subEnd = "]]>";
      int b = v1.indexOf(subEnd);
      if(b>= 0){
          v2 = v1.substring(0,b);
      }
      return v2;

    }

    /**
     * Convert a bound type to a value type.
     *
     * @param v The value to be convereted. Can be null.
     * @throws Exception if there's an error during the conversion. The caller is responsible for
     *                   reporting the error to the user through {@link ValidationEventHandler}.
     */
    @Override
    public String marshal(String v) throws Exception {

        logger.info("对象转换xml:"+"<![CDATA["+ v +"]]>");
        return "<![CDATA["+ v +"]]>";
    }
}
